//
//  CameraViewController.swift
//  Monosaccharides
//
//  Created by iSolar on 2017/11/15.
//  Copyright © 2017年 nothing. All rights reserved.
//

import UIKit
import SVProgressHUD
import MobileCoreServices
import AVFoundation

class CameraViewController: BaseViewController {

    var cameraView = CameraView()
    var imagePickerVC = UIImagePickerController()
    var switchView = UIView()
    var flashButton = UIButton()
    var flashSelectedButton = UIButton()
    var tapNum = NSInteger()
    let defaults = UserDefaults.standard
    var timeLabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "调用系统相册、相机"

        cameraView = CameraView.init(frame: CGRect.init(x: 0, y: 100, width: KWidth, height: 240))
        cameraView.backgroundColor = UIColor.yellow
        view.addSubview(cameraView)
        cameraView.photoButton.addTarget(self, action: #selector(systemPhotoAction), for: .touchUpInside)
        cameraView.cameraButton.addTarget(self, action: #selector(systemCameraAction), for: .touchUpInside)
        cameraView.customCameraViewBtn.addTarget(self, action: #selector(customCamereView), for: .touchUpInside)
        
    }
    

}


extension CameraViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    @objc func systemPhotoAction() {
        let vc = UIImagePickerController()
        vc.delegate = self
        vc.hidesBottomBarWhenPushed = true
        present(vc, animated: true, completion: nil)
        
    }
    
    @objc func systemCameraAction() {
        
        if isSimulator() {
            
            SVProgressHUD.showError(withStatus: "该设备相机不能调用！")
            
            return
        }
        let vc = UIImagePickerController()
        vc.sourceType = .camera
        vc.allowsEditing = true
        vc.cameraDevice = .rear
        vc.cameraFlashMode = .on
        vc.delegate = self
        vc.hidesBottomBarWhenPushed = true
        present(vc, animated: true, completion: nil)
        
    }
    
    @objc func customCamereView() {
        
        
        if isSimulator() {
            
            SVProgressHUD.showError(withStatus: "该设备相机不能调用！")
            
            return
        }
        imagePickerVC.sourceType = .camera
        // 设置是否显示系统的相机页面（我们要定制则返回false）
        imagePickerVC.showsCameraControls = false
        // 拍照界面容器
        let customView = UIView.init(frame: UIScreen.main.bounds)
        
        let topView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: KWidth, height: 40))
        customView.addSubview(topView)
        topView.backgroundColor = UIColor.black
        flashButton = UIButton.init(frame: CGRect.init(x: 20, y: 0, width: 40, height: 40))
        topView.addSubview(flashButton)
        flashButton.tag = 4
        flashButton.setImage(UIImage.init(named: "normal"), for: .normal)
        if (defaults.integer(forKey: "flashType") == 0) {
            flashButton.setImage(UIImage.init(named: "normal"), for: .normal)
        } else if (defaults.integer(forKey: "flashType") == 1) {
            flashButton.setImage(UIImage.init(named: "turnon"), for: .normal)
        } else if (defaults.integer(forKey: "flashType") == 2) {
            flashButton.setImage(UIImage.init(named: "turnoff"), for: .normal)
        }
        flashButton.addTarget(self, action: #selector(takePhotoOrVideo(_:)), for: .touchUpInside)
        
        let cancleButton = UIButton.init(frame: CGRect.init(x: KWidth - 60, y: 0, width: 40, height: 40))
        topView.addSubview(cancleButton)
        cancleButton.tag = 5
        cancleButton.setTitleColor(UIColor.white, for: .normal)
        cancleButton.setTitle("取消", for: .normal)
        cancleButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        cancleButton.addTarget(self, action: #selector(takePhotoOrVideo(_:)), for: .touchUpInside)
        
        switchView = UIView.init(frame: CGRect.init(x: (KWidth - 150)/2, y: 0, width: 150, height: 40))
        topView.addSubview(switchView)
        switchView.isHidden = true
        tapNum = 0
        
        var titleArr = NSArray()
        titleArr = ["自动","打开","关闭"]
        
        for i in 0..<titleArr.count {
            
            let flashTypeButton = UIButton.init(frame: CGRect.init(x: 50*i, y: 0, width: 50, height: 40))
            flashTypeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            flashTypeButton.setTitle(titleArr[i] as? String, for: .normal)
            if (defaults.integer(forKey: "flashType") == 0) {
                if i == 0 {
                    flashTypeButton.isSelected = true
                } else {
                    flashTypeButton.isSelected = false
                }
            } else if (defaults.integer(forKey: "flashType") == 1) {
                if i == 1 {
                    flashTypeButton.isSelected = true
                } else {
                    flashTypeButton.isSelected = false
                }
            } else if (defaults.integer(forKey: "flashType") == 2) {
                if i == 2 {
                    flashTypeButton.isSelected = true
                } else {
                    flashTypeButton.isSelected = false
                }
            }
            flashTypeButton.setTitleColor(UIColor.white, for: .normal)
            flashTypeButton.setTitleColor(UIColor.yellow, for: .selected)
            flashTypeButton.tag = i + 10
            flashTypeButton.addTarget(self, action: #selector(flashModelAction(_:)), for: .touchUpInside)
            if (flashTypeButton.isSelected) {
                flashSelectedButton = flashTypeButton
            }
            switchView.addSubview(flashTypeButton)
            
        }
        
        // 开始摄像按钮（如果是拍照，则不需要此按钮）
        let startVideo = UIButton.init(frame: CGRect.init(x: (KWidth - 50 * 3)/4, y: KHeight - 80, width: 50, height: 50))
        // 停止摄像按钮（如果是拍照，则不需要此按钮）
        let stopVideo = UIButton.init(frame: CGRect.init(x: (KWidth - 50 * 3)/2 + 50, y: KHeight - 80, width: 50, height: 50))
        // 拍照按钮（如果是摄像，则不需要此按钮）
        let takePhoto = UIButton.init(frame: CGRect.init(x: (KWidth - 50 * 3)*3/4 + 50*2, y: KHeight - 80, width: 50, height: 50))
        
        // 录像时长
        timeLabel = UILabel.init(frame: CGRect.init(x: 20, y: KHeight - 120, width: KWidth - 40, height: 20))
        timeLabel.font = UIFont.systemFont(ofSize: 13)
        timeLabel.textColor = UIColor.white
        timeLabel.textAlignment = .center
        
        customView.addSubview(startVideo)
        customView.addSubview(stopVideo)
        customView.addSubview(takePhoto)
        
        startVideo.tag = 1
        stopVideo.tag = 2
        takePhoto.tag = 3
        
        startVideo.setTitle("开始", for: .normal)
        stopVideo.setTitle("停止", for: .normal)
        takePhoto.setTitle("拍照", for: .normal)
        
        startVideo.addTarget(self, action: #selector(takePhotoOrVideo(_:)), for: .touchUpInside)
        stopVideo.addTarget(self, action: #selector(takePhotoOrVideo(_:)), for: .touchUpInside)
        takePhoto.addTarget(self, action: #selector(takePhotoOrVideo(_:)), for: .touchUpInside)
        
        // 将自定义的相机界面赋值给cameraOverlayView属性即可显示自定义界面
        imagePickerVC.cameraOverlayView = customView
        imagePickerVC.cameraFlashMode = .auto
        //设定录像的媒体类型
        imagePickerVC.mediaTypes = [kUTTypeMovie as String]
        //设置摄像头捕捉模式为录像
        imagePickerVC.cameraCaptureMode = .video
        //设置视频质量
        imagePickerVC.videoQuality = .typeMedium
        //视频的最大时长
        imagePickerVC.videoMaximumDuration = 10
        //允许用户编辑
        imagePickerVC.allowsEditing = true
        
        // 此属性可transform自定义界面
        imagePickerVC.cameraViewTransform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
        imagePickerVC.delegate = self
        imagePickerVC.hidesBottomBarWhenPushed = true
        present(imagePickerVC, animated: true, completion: nil)
        
    }
    
    @objc func takePhotoOrVideo(_ sender: UIButton) {
    
        switch sender.tag {
        case 1:
            
            imagePickerVC.startVideoCapture()
            
            break
            
        case 2:
            
            imagePickerVC.stopVideoCapture()
            
            break
            
        case 3:
            
            imagePickerVC.takePicture()
            
            break
            
        case 4:

            if tapNum%2 == 0 {
                switchView.isHidden = false
            } else {
                switchView.isHidden = true
            }
            tapNum = tapNum + 1
            
            break
            
        case 5:
            
            imagePickerVC.dismiss(animated: true, completion: nil)
            
            break
            
        default:
            break
        }
    
    }
    
    @objc func flashModelAction(_ sender: UIButton) {
        
        tapNum = tapNum - 1
        print("----------\(sender.tag)----------\(tapNum)-----------")

        if !sender.isSelected {
            flashSelectedButton.isSelected = !flashSelectedButton.isSelected
            sender.isSelected = !sender.isSelected
            flashSelectedButton = sender
            
            switch sender.tag {
            case 10:
                
                imagePickerVC.cameraFlashMode = .auto
                flashButton.setImage(UIImage.init(named: "normal"), for: .normal)
                
                defaults.set(0, forKey: "flashType")
                
                break
                
            case 11:
                
                imagePickerVC.cameraFlashMode = .on
                flashButton.setImage(UIImage.init(named: "turnon"), for: .normal)
                defaults.set(1, forKey: "flashType")
                
                break
                
            case 12:
                
                imagePickerVC.cameraFlashMode = .off
                flashButton.setImage(UIImage.init(named: "turnoff"), for: .normal)
                defaults.set(2, forKey: "flashType")
                
                break
                
            default:
                break
            }
            
            
        }
        
        switchView.isHidden = true
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let mediaType = info[UIImagePickerControllerMediaType] as! String
        print(mediaType)
        if mediaType == (kUTTypeImage as String) {
            let imagePickerc = info[UIImagePickerControllerOriginalImage] as! UIImage
            self.cameraView.photoImage.image = imagePickerc
        } else if mediaType == (kUTTypeMovie as String) {
            let url: URL = info[UIImagePickerControllerMediaURL] as! URL
            let path: String = url.path

            let opts:[String : Any] = NSDictionary.init(object: NSNumber.init(value: false), forKey: AVURLAssetPreferPreciseDurationAndTimingKey as NSCopying) as! [String : Any]
            let urlAsset:AVURLAsset = AVURLAsset.init(url: url, options: opts)
            // 初始化视频媒体文件
            var second: Int = 0
            var minute: Int = 0
            
            // 获取视频总时长,单位秒
            second = Int(urlAsset.duration.value) / Int(urlAsset.duration.timescale)
            minute = second/60
            if (second > 9) {
                cameraView.timeLabel.text = "视频时长： \(minute):\(second)"
            } else {
                cameraView.timeLabel.text = "视频时长： \(minute):0\(second)"
            }
            
            //判断能否保存到相簿
            if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) {
                //保存视频到相簿
                UISaveVideoAtPathToSavedPhotosAlbum(path,
                                                    self,
                                                    #selector(video(videoPath:didFinishSavingWithError:contextInfo:)),
                                                    nil)
            }
        }
        
        self.dismiss(animated: true, completion: nil)
        
    }
    
    func video(videoPath: String, didFinishSavingWithError error: NSError, contextInfo info: AnyObject) {
        
        print("视频保存成功")
    }
    
    func isSimulator() -> Bool {
        var isSim = false
        #if arch(i386) || arch(x86_64)
            isSim = true
        #endif
        return isSim
    }

}

